package com.cat.paxos.proposal;

import com.alibaba.fastjson.JSONObject;

import java.io.Serializable;

/**
 * @auther Cat.wang
 * @date 2020/1/15 16:23
 */
public class ObjectPayloadSerializer implements PayloadSerializer<Object> {

    public static final String SPLIT = ":";

    @Override
    public <D extends Serializable> D encode(Object data) {
        return (D) (data == null ? null : String.format("%s%s%s", JSONObject.toJSONString(data), SPLIT, data.getClass().getName()));
    }

    @Override
    public <D extends Serializable> Object decode(D data) {

        if (data == null) {
            return null;
        }

        String dataStr = data.toString();

        int index = dataStr.lastIndexOf(SPLIT);
        if (index < 0 || dataStr.length() <= index + 1) {
            throw new IllegalArgumentException();
        }

        try {
            return JSONObject.parseObject(dataStr.substring(0, index), Class.forName(dataStr.substring(index + 1)));
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException(e);
        }
    }
}
